package edu.umassd.raddacl.util;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public final class FilesUtil
{
	/**
	 * Changes the extension of the file from whatever it is to the provided
	 * extension. If the incoming file does not have an extension, then it adds
	 * one.
	 * 
	 * @param location
	 *            - the location of the file.
	 * @param extension
	 *            - the new extension to add to the file.
	 * @return a path to the new file.
	 * @throws IllegalArgumentException
	 *             if the provided path is a file.
	 */
	public static Path changeExtension(Path location, String extension)
	{
		if (Files.isDirectory(location))
		{
			throw new IllegalArgumentException("The provided path \""
					+ location.toString()
					+ "\" is a directory, but should be a file.");
		}

		String fileName = getName(location);
		String newExtension = extension == null ? "" : "." + extension;

		return Paths.get(location.getParent().toString(), fileName
				+ newExtension);
	}

	/**
	 * Gets the name of a file, without its extension.
	 * 
	 * @param pathToFile
	 *            - the path to the file.
	 * @return the name of the file without its extension. This means the full
	 *         filename without any characters after the last period
	 *         (inclusive).
	 */
	public static String getName(Path pathToFile)
	{
		String fileName = pathToFile.getFileName().toString();
		int value = fileName.lastIndexOf(".");

		if (value != -1)
		{
			fileName = fileName.substring(0, value);
		}

		return fileName;
	}
}
